package com.aaa.shuke2024.service.impl;

import com.aaa.shuke2024.entity.User;
import com.aaa.shuke2024.dao.UserDao;
import com.aaa.shuke2024.service.UserService;
import com.aaa.shuke2024.utils.MyTools;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author teacherChen
 * @since 2024-12-02 16:09:11
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        return this.userDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<User> queryByPage(User user, PageRequest pageRequest) {
        long total = this.userDao.count(user);
        return new PageImpl<>(this.userDao.queryAllByLimit(user, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        //添加用户之前，需要将明文密码加密
        String salt = MyTools.getSalt();
        String password = MyTools.makePassword(user.getPassword(), salt);
        user.setPassword(password);
        user.setSalt(salt);
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        //如果修改密码，对新密码进行加密
         //获取新密码
        String passwordNew = user.getPassword();
        //获取老密码
        User oldUser=this.queryById(user.getId());
        String passwordOld = oldUser.getPassword();
        if(passwordOld.equals(passwordNew)){
            //不需要密码加密
            user.setSalt(oldUser.getSalt());
        }else{
            //需要密码加密
            String salt = MyTools.getSalt();
            user.setPassword(MyTools.makePassword(user.getPassword(),salt));
            user.setSalt(salt);
        }
        this.userDao.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userDao.deleteById(id) > 0;
    }

    @Override
    public User findUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        //根据用户查询的对象
        return userDao.findUserByUsernameAndPassword(username,password);
    }
}
